import { BeforeApplicationShutdown, Module, OnApplicationBootstrap, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
// 环境配置模块
import { ConfigModule, ConfigService } from '@nestjs/config';
// 数据库模块
import { TypeOrmModule } from '@nestjs/typeorm';

// 模块
import { UserModule } from './modules/user/user.module';
import { AuthModule } from './modules/auth/auth.module';
import { MenuModule } from './modules/menu/menu.module';
import { RoleModule } from './modules/role/role.module';

// 鉴权守卫
import { AuthGuard } from "./modules/auth/auth.guard"
import { APP_GUARD } from '@nestjs/core';

// 实体
import { User } from './modules/user/entities/user.entity';

import { Role } from './modules/role/entities/role.entity';

import { Menu } from './modules/menu/entities/menu.entity';
import { Meta } from './modules/menu/entities/meta.entity';
import { Permission } from './modules/menu/entities/menu.permission.entity';

// 当前环境
const NODE_ENV = process.env.NODE_ENV
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `./config/.env.${NODE_ENV}`,
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql', // 数据库类型
        entities: [User, Role, Menu, Meta, Permission],  // 数据表实体
        host: configService.get('DB_HOST', 'localhost'), // 主机，默认为localhost
        port: configService.get<number>('DB_PORT', 3306), // 端口号
        username: configService.get('DB_USER', 'root'),   // 用户名
        password: configService.get('DB_PASSWORD', "123123"), // 密码
        database: configService.get('DB_DATABASE', 'nestadmin'), //数据库名
        timezone: '+08:00', //服务器上配置的时区
        autoLoadEntities: true,//自动加载实体
        synchronize: true, //根据实体自动创建数据库表， 生产环境建议关闭
      }),
    }),
    UserModule,
    AuthModule,
    MenuModule,
    RoleModule
  ],
  controllers: [AppController],
  providers: [AppService, {
    provide: APP_GUARD,
    useClass: AuthGuard,
  },],
})
export class AppModule implements
  OnModuleInit,
  OnApplicationBootstrap,
  OnModuleDestroy,
  BeforeApplicationShutdown {
  onModuleInit() {
    console.log("module初始化");
  }

  onApplicationBootstrap() {
    console.log("module初始化完成");
  }

  onModuleDestroy() {
    console.log("module销毁");
  }

  beforeApplicationShutdown() {
    console.log("module关闭");
  }
}
